package com.mxpio.erp.equipment.job;

import cn.hutool.core.date.DateUtil;
import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentRepair;
import com.mxpio.erp.common.equipment.entity.EquipmentRepairOperation;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

//维修工单，提交验收后，超24小时，自动验收。默认验收人使用8888自动化助手账号
@Slf4j
@Component
public class EquipmentRepairAutoCheckJob implements Job {

    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("维修任务自动验收job执行开始："+DateUtil.formatDateTime(new Date()));
        Object params = context.getJobDetail().getJobDataMap().get("params");
        Integer offSetHour = 24;//默认24小时，可以在任务中配置
        if (params!=null&& StringUtils.isNumeric(params.toString())){
            offSetHour = Integer.parseInt(params.toString());
        }
        String hoursBefore = DateUtil.formatDateTime(DateUtils.addHours(new Date(),0-offSetHour));
        Criteria dateCriteria = Criteria.create();
        dateCriteria.addCriterion("updateTime", Operator.LT,hoursBefore);
        List<EquipmentRepair> repairList = JpaUtil.linq(EquipmentRepair.class).equal("repairStatus", EquipmentEnums.RepairStatus.CHECK.getCode()).where(dateCriteria).list();
        if (repairList.size()>0){
            for (EquipmentRepair repair:repairList){
                String checkResult = "已修复";
                repair.setIsUsable(1);//默认为已修复
                repair.setRepairStatus(EquipmentEnums.RepairStatus.REPORT.getCode());
                repair.setCheckTime(new Date());
                repair.setCheckUser("8888");
                JpaUtil.update(repair);

                //设置操作记录
                EquipmentRepairOperation operation = new EquipmentRepairOperation();
                //设置维修ID
                operation.setBizNo(repair.getBizNo());
                //设置操作名称
                operation.setOperate("维修验收");
                //设置操作原因
                operation.setReason("维修验收结果："+checkResult);
                //设置操作时间
                operation.setOperateTime(new Date());
                //设置操作人
                operation.setOperator("自动化助手" + "/" + 8888);
                JpaUtil.save(operation);
            }
        }
        log.info("维修任务自动验收job执行结束："+DateUtil.formatDateTime(new Date()));
    }
}
